﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace Send
{
    public partial class Form1 : Form
    {
        static Stream fs = null;
        int nameLen = 0;
        List<byte> name;
        long contentLen = 0;
        List<byte> content;
        public Form1()
        {
            InitializeComponent();
        }
    
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtIP.Text.Trim()))
            {
                MessageBox.Show("请输入IP地址:"); return;
            }
            //实例化一个基于TCP/IP的基于流的套接字
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Parse(txtIP.Text), 10000);
            sock.Connect(endPoint);
            //组建数据包
            //文件长度
            contentLen = fs.Length;
            //文件内容         
            sock.Send(BitConverter.GetBytes(contentLen));
            //循环发送文件内容
            while (true)
            {
                byte[] bits = new byte[256];
                int r = fs.Read(bits, 0, bits.Length);
                if (r <= 0) break; //如果从流中读取完毕,则break;
                sock.Send(bits, r, SocketFlags.None);
            }
            sock.Close();
            //由于读取操作会是文件指针产生偏移,最后读取结束之后,要将指针置为0;
            fs.Position = 0;
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "只能发送图片文件|*.png;*.jpg;*.gif|All Files|*.*";
            if (DialogResult.OK == dlg.ShowDialog())
            {
                fs = dlg.OpenFile();
                txtPath.Text = dlg.FileName;
                //文件名长度
                nameLen = Path.GetFileName(dlg.FileName).Length;
                //文件名内容
                Encoding encoding = new UTF8Encoding();
                //将文件名转换为字节
                name = encoding.GetBytes(Path.GetFileName(dlg.FileName)).ToList();
            }
        }

        //利用下边的代码可以实时的将桌面截图发给远方,实现桌面的远程监控
        private void Form1_Load(object sender, EventArgs e)
        {
            //获取主屏
            Screen s = Screen.PrimaryScreen;
            //创建一个位图,将其大小设置为何屏幕大小一致,为了获取屏幕的图片
            Bitmap bit = new Bitmap(s.Bounds.Width,s.Bounds.Height);
            //利用当前bit获取一个画布,画布已经于Graphics对象关联
            Graphics g = Graphics.FromImage(bit); 
            //将屏幕的(0,0)坐标截图内容copy到画布的(0,0)位置,尺寸到校 bit.size;
            g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bit.Size);
            //将位图保存到D盘
            bit.Save("D:\\123.jpg"); 
            //释放位图资源
            bit.Dispose(); 
            //释放画布
            g.Dispose();
        }
    }
}
